#!/bin/bash
set -e
source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/./common.sh"

#下载依赖和工具包
function install_development() {
  sudo yum install -y wget tar  patch 
  source /etc/profile
}

#获取fastx_toolkit
function download_fastx_toolkit() {
  echo "# fastx_toolkit正在下载"
  cp "$2"/src/fastx_toolkit-0.0.14.tar.bz2 "$1"
  cp "$2"/src/GDGraph.zip "$1"  #以便在run.sh 安装perl相关依赖
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# fastx_toolkit已经下载成功\033[0m"
  else
    echo -e "\033[31m# fastx_toolkit下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_fastx_toolkit() {
  echo "# fastx_toolkit正在安装"
  export PKG_CONFIG_PATH="$2"/libgtextutils-0.7/lib/pkgconfig:$PKG_CONFIG_PATH
  tar -xjvf "$1"/fastx_toolkit-0.0.14.tar.bz2 -C "$1" && rm -f "$1"/fastx_toolkit-0.0.14.tar.bz2
  cd "$1"/fastx_toolkit-0.0.14
  mkdir -p  "$2"/fastx_toolkit-0.0.14/galaxy
  cp -r "$1"/fastx_toolkit-0.0.14/galaxy/* "$2"/fastx_toolkit-0.0.14/galaxy
  mkdir "$2"/fastx_toolkit-0.0.14/src/
  cp "$1"/GDGraph.zip  "$2"/fastx_toolkit-0.0.14/src/  #以便在run.sh 安装perl相关依赖
  CC=clang CXX=clang++ ./configure --prefix="$2"/fastx_toolkit-0.0.14 --build=aarch64-unknown-linux-gnu  --enable-static=yes  --enable-shared CFLAGS="-march=armv8.2-a -fsigned-char -ffp-contract=off -Wno-pragma-pack"  CXXFLAGS="-march=armv8.2-a -fsigned-char -ffp-contract=off -Wno-pragma-pack"   CC=clang CXX=clang++
  make
  make install
  echo -e "\033[1;32;1m# fastx_toolkit已经安装完毕\033[0m"
}

# 创建modulefiles文件
function write_fastx_toolkit_module() {
  cat >"$1/fastx_toolkit-0.0.14/fastx_toolkit_modulefiles"<<EOF
#%Module1.0
conflict fastx_toolkit
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set FASTX \$pwd
setenv FASTX \$FASTX
prepend-path PATH \$FASTX/bin
EOF
}

function main() {
  is_check_build_install_directory "$1" "$2" "fastx_toolkit-0.0.14.sh"
  is_equal_build_install_path "$1" "$2"
  install_development
  download_fastx_toolkit "$1" "$3"
  install_fastx_toolkit "$1" "$2"
  write_fastx_toolkit_module "$2"
  rm -rf "$1"/fastx_toolkit-0.0.14
}

main "$@"